#include "config.h"

#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <getopt.h>
#include <dirent.h>
#include <ctype.h>

#define DBG_SUBSYS S_LIBINTERFACE

#include "configure.h"
#include "regex.h"
#include "env.h"
#include "adt.h"
#include "cluster.h"
#include "lichstor.h"
#include "net_global.h"
#include "utils.h"
#include "dbg.h"
#include "etcd.h"

int lich_auth_set(char *key, char *value)
{
        int ret;

        ret = etcd_create_text(ETCD_CHAP, key, value, 0);
        if (unlikely(ret))
                GOTO(err_ret, ret);

        return 0;
err_ret:
        return ret;
}

int lich_auth_update(char *key, char *value)
{
        int ret;

        if (strcmp(value, "") == 0) {
                printf("value can't be empty.\n");
                ret = EPERM;
                GOTO(err_ret, ret);
        }

        ret = etcd_update_text(ETCD_CHAP, key, value, NULL, 0);
        if (unlikely(ret))
                GOTO(err_ret, ret);

        return 0;
err_ret:
        return ret;
}

int lich_auth_get(char *key)
{
        int ret;
        char value[MAX_NAME_LEN * 2];

        ret = etcd_get_text(ETCD_CHAP, key, value, NULL);
        if (unlikely(ret))
                GOTO(err_ret, ret);

        printf("%s\n", value);

        return 0;
err_ret:
        return ret;
}

int lich_auth_remove(char *key)
{
        int ret;

        ret = etcd_del(ETCD_CHAP, key);
        if (unlikely(ret))
                GOTO(err_ret, ret);

        return 0;
err_ret:
        return ret;
}

int lich_auth_list()
{
        int ret, i;
        etcd_node_t *list = NULL, *node;

        ret = etcd_list(ETCD_CHAP, &list);
        if (unlikely(ret))
                GOTO(err_ret, ret);

        for (i = 0; i < list->num_node; i++) {
                node = list->nodes[i];
                printf("%s\n", node->key);
        }

        free_etcd_node(list);
        return 0;
err_ret:
        return ret;
}
